package cn.itsource.pet.service.impl;

import cn.itsource.basic.dto.Point;
import cn.itsource.basic.exception.BusinessException;
import cn.itsource.basic.service.IBaiduAiAuditService;
import cn.itsource.basic.util.*;
import cn.itsource.order.domain.OrderPetAcquisition;
import cn.itsource.order.mapper.OrderPetAcquisitionMapper;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.pet.domain.Pet;
import cn.itsource.pet.domain.SearchMasterMsg;
import cn.itsource.pet.domain.SearchMasterMsgAuditLog;
import cn.itsource.pet.mapper.PetMapper;
import cn.itsource.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.itsource.pet.mapper.SearchMasterMsgMapper;
import cn.itsource.pet.query.SearchMasterMsgQuery;
import cn.itsource.pet.service.ISearchMasterMsgService;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.mapper.UserMapper;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;

    @Override
    public AjaxResult publish(SearchMasterMsg query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.findByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        searchMasterMsgMapper.add(query);

        Boolean bool1 = baiduAiAuditService.textAudit(query.getTitle());
        Boolean bool2 = baiduAiAuditService.imageAudit(query.getResources());

        SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
        log.setMsgId(query.getId());
        if(bool1&&bool2){
            //审核通过
            query.setState(1);
            log.setState(1);
            log.setNote("发布成功");
            searchMasterMsgAuditLogMapper.add(log);

            List<Shop> shops = shopMapper.findAll();
            Point point = DistanceUtils.getPoint(query.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shops);

            if(nearestShop==null){
                //修改状态
                query.setState(3);
            }else {
                query.setShopId(nearestShop.getId());
                Employee employee = employeeMapper.findById(nearestShop.getAdminId());
//                SmsUtils.sendSms(employee.getPhone(),"快去"+query.getAddress()+"接你的祖宗");
                System.out.println("快去"+query.getAddress()+"接你的祖宗");
            }
            searchMasterMsgMapper.update(query);

        }else {
            //审核失败
            query.setState(-1);
            log.setState(0);
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.add(log);
            searchMasterMsgMapper.delete(query.getId());

            System.out.println("发布失败，请重新修改信息重新发布");
            return AjaxResult.me().setSuccess(false).setMessage("寻主消息发布失败");
        }
        return AjaxResult.me();
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        //用户不需要设置state，用户是查询自己的所有状态的寻主消息
        //获取用户的id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.findByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        //分页查询
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询待处理的寻主消息
        query.setState(1);
        //用于区分平台管理员或店铺管理员
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        //如果shopId is null = 平台管理员
        query.setShopId(employee.getShopId());

        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> pool(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(3);

        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        query.setShopId(employee.getShopId());

        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(2);

        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        query.setShopId(employee.getShopId());

        return super.queryPage(query);
    }

    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    @Override
    @Transactional
    public void accept(Map<String, String> map) {
        Long msgId = Long.parseLong(map.get("msgId"));
        Long empId = Long.parseLong(map.get("handler"));
        String note = map.get("note");
        //一：校验当前订单是否已经在处理
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadByMsgId(msgId);
        //如果是待处理的订单，并且这个订单正在处理 - 不会生成新的订单
        if(order!=null){//已经由订单 = 寻主消息正在处理
            throw new BusinessException("订单正在处理，请勿重复接单...");
        }

        //二：通过msgId生成宠物，录入到系统
        SearchMasterMsg msg = searchMasterMsgMapper.findById(msgId);
        Pet pet = msg2Pet(msg);
        petMapper.add(pet);

        //三：生成收购订单
        OrderPetAcquisition orderTem = buildOrderPetAcquisition(msg,pet,empId,note);
        orderPetAcquisitionMapper.add(orderTem);

        //四：通过处理人去收回宠物
        //Employee employee = employeeMapper.loadById(empId);
        //SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请及时处理，地址："+msg.getAddress());
        System.out.println("你有新的订单，请及时处理，地址："+msg.getAddress());
    }

    private OrderPetAcquisition buildOrderPetAcquisition(SearchMasterMsg msg, Pet pet, Long empId, String note) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(msg.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(msg.getName()+"收购订单");
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 1000*60*60*24*2));
        order.setState(0);//待处理
        order.setPrice(msg.getPrice());
        //        order.setPaytype(); //现金支付
        order.setPetId(pet.getId());
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(empId);
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }

    private Pet msg2Pet(SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice());
        pet.setTypeId(msg.getPetType());
        pet.setResources(msg.getResources());
        pet.setState(0);
        pet.setShopId(msg.getShopId());
        //这里是领养人 - 宠物还没有被领养，所以没有
        //pet.setUserId(msg.getUserId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;
    }
}
